﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;

namespace BaicaiTianqi.Model
{
    /// <summary>
    /// 异步HTTP请求辅助类
    /// </summary>
    public class HttpHelper
    {
        public delegate void HandleResult(string result);
        private HandleResult handle;
        public void StartRequest(string Url, HandleResult handle)
        {
            this.handle = handle;
            var webRequest = (HttpWebRequest)WebRequest.Create(Url);
            webRequest.Method = "GET";
            try
            {
                webRequest.BeginGetResponse(new AsyncCallback(HandleResponse), webRequest);
            }
            catch
            {
            }
        }

        public void HandleResponse(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest httpRequest = null;
                HttpWebResponse httpResponse = null;
                string result = string.Empty;
                try
                {
                    httpRequest = (HttpWebRequest)asyncResult.AsyncState;
                    httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(asyncResult);
                    using (var reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                        reader.Close();
                    }
                }
                catch
                {
                }
                finally
                {
                    if (httpRequest != null) httpRequest.Abort();
                    if (httpResponse != null) httpResponse.Close();
                }
                result = result.Substring(15, result.Length - 16);
                handle(result);
            }
            catch 
            {
            }
        }
    }
}
